package com.sw.haruka.module.search;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.shqyang.yexplorer.manager.ExplorerManager;
import com.sw.haruka.R;
import com.sw.haruka.dal.HarukaConfig;
import com.sw.haruka.helper.utils.FileUtils;
import com.sw.haruka.helper.utils.HarukaHandlerConstant;
import com.sw.haruka.helper.utils.Configuration;
import com.sw.haruka.module.base.BaseFragment;
import com.sw.haruka.module.search.manager.FileScanManager;
import com.sw.haruka.module.search.manager.FileScanObserver;
import com.sw.haruka.view.MainActivity;

import java.io.File;
import java.lang.ref.WeakReference;

public class SearchFragment extends BaseFragment implements FileScanObserver {

    private final String TAG = this.getClass().getName();

    private RelativeLayout mSearchBox;
    private EditText mSearchInput;
    private ImageButton mClear;
    private TextView mResultTextView;
    private SearchHandler mHandler;

    private ExplorerManager manager;
    private String mKey = "";

    @Override
    protected int layoutId() {
        return R.layout.search_fragment;
    }

    @Override
    protected void initView() {
        FileScanManager.getInstance().addObserver(this);
        mHandler = new SearchHandler(this);
        mSearchBox = mRootView.findViewById(R.id.relativeLayout_search);
        mSearchInput = mRootView.findViewById(R.id.editText_input);
        mClear = mRootView.findViewById(R.id.imageButton_clear);
        mResultTextView = mRootView.findViewById(R.id.textView_result);
        manager = ExplorerManager.getInstance();
    }

    @Override
    protected void initEvent() {
        mSearchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                if (mHandler.hasMessages(HarukaHandlerConstant.SEARCH_FILE)) {
                    mHandler.removeMessages(HarukaHandlerConstant.SEARCH_FILE);
                    FileUtils.isSearching = false;
                }
                if (s.toString().trim().length() > 0) {
                    mHandler.sendEmptyMessageDelayed(HarukaHandlerConstant.SEARCH_FILE, 1000);
                    mClear.setVisibility(View.VISIBLE);
                } else {
                    mClear.setVisibility(View.INVISIBLE);
                    FileScanManager.getInstance().cancel();
                }
            }
        });
        mClear.setOnClickListener(v -> mSearchInput.setText(""));

        Button cancel = mRootView.findViewById(R.id.btn_no);
        cancel.startAnimation(AnimationUtils.makeInAnimation(mContext, false));
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消
                reset();
                ((MainActivity)mActivity).exitFragment();
            }
        });
        mSearchBox.startAnimation(AnimationUtils.makeInAnimation(mContext, true));
    }

    @Override
    protected void loadData(boolean isRefresh) {
        manager.setSearchMode();
    }

    private static class SearchHandler extends Handler {
        private WeakReference<Fragment> reference;

        public SearchHandler(Fragment fragment) {
            reference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case HarukaHandlerConstant.SEARCH_FILE: {
                    ((SearchFragment) reference.get()).search();
                    break;
                }
            }
        }
    }

    public void search() {
        mKey = mSearchInput.getText().toString().trim();
        if (mKey.length() == 0) {
            return;
        }
        manager.clearList();
        Log.i(TAG, "search: 查找任务执行----------> " + mKey);
        FileScanManager.getInstance().scan(HarukaConfig.ROOT_PATH);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void scanStart() {
        Log.i(TAG, "search: 开始查找-----------");
        requireActivity().runOnUiThread(()->{
            mResultTextView.setText("包含\"" + mKey + "\"的关键字的文件(0项)");
        });
    }

    private void reset() {
        mSearchInput.setText("");
        mResultTextView.setText("");
        manager.clearList();
    }

    @Override
    public void scanned(File file) {
        String tK = mKey;
        if (!file.getName().toLowerCase().contains(tK.toLowerCase())) {
            return;
        }
        if (!Configuration.INSTANCE.getBoolean(Configuration.Keys.ShowHiddenFile)
                && file.getName().startsWith(".")) {
            return;
        }
        mActivity.runOnUiThread(()-> {
            manager.addFileToList(file);
            mResultTextView.setText(String.format("包含\"%s\"的关键字的文件(%d项)", tK, manager.getListSize()));
        });
        Log.i(TAG, "search: 找到文件" + file.getName());
    }

    @Override
    public void scanEnd() {
        Log.i(TAG, "search: 查找完毕");
        String tK = mKey;
        mActivity.runOnUiThread(() -> {
            mResultTextView.setText(String.format("包含\"%s\"的关键字的文件(%d项)", tK, manager.getListSize()));
        });
    }

    @Override
    public void cancel() {
        Log.i(TAG, "search: 已取消");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        FileScanManager.getInstance().removeObserver(this);
    }
}
